//
//  MusicPlayerViewController.m
//  Movie
//
//  Created by cjy on 16/3/24.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "MusicPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ModelTrailer.h"
#import "SVProgressHUD.h"
#import "MusicPlayerTableViewCell.h"
#import "MusicSegTableViewCell.h"
#import "landscape.h"
#import "MHNetWorkTask.h"
#import "KSBarrageView.h"

@interface MusicPlayerViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)NSMutableArray *arrDanmusssss;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,retain) NSMutableArray *array;

@property (nonatomic,strong) NSMutableArray *arrSeg;

@property (nonatomic,assign)BOOL isPlay;
@property (nonatomic,strong) UIView *playerView;
@property (nonatomic,retain) AVPlayer *player;
@property (nonatomic,retain) AVPlayerLayer *playerLayer;
@property (nonatomic,retain) AVPlayerItem *playerItem;
@property (nonatomic, assign) CGFloat totalMovieDuration; // 保存该视频资源的总时长，快进或快退的时候要用
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *playerButton;
@property (nonatomic, strong) UILabel *timeLabel;
@property(nonatomic,assign)BOOL isTap;
@property (nonatomic,strong) UIImageView *background;

@property (nonatomic, strong) UIVisualEffectView *visualView;
@property (nonatomic, strong) UISegmentedControl *seg;

#define screenFrame [UIScreen mainScreen].bounds


@end

@implementation MusicPlayerViewController


- (void)viewWillAppear:(BOOL)animated{

}

- (void)viewWillDisappear:(BOOL)animated{

    [self.player pause];
//    self.player = nil;
//
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    [self addAVPlayer];
    //播放
    [self.player play];

    //添加通知
    [self addNotificationCenters];
    
    //添加进度观察
    [self addProgressObserver];
    
    //添加手势
    [self addGestureRecognizer];
//
    self.background = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"asd"]];
    self.background.frame = CGRectMake(0, 280, self.view.frame.size.width, 500);
    [self.view addSubview:self.background];
    self.background.userInteractionEnabled = YES;
    
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:2];
    self.visualView = [[UIVisualEffectView alloc] init];
    self.visualView.frame = CGRectMake(0, 0, self.view.frame.size.width, 400);
    self.visualView.effect = blur;
    
    [self.background addSubview:self.visualView];

    [self createSegment];

}




- (void)createSegment{

    _seg = [[UISegmentedControl alloc]initWithItems:@[@"MV描述",@"查看评论"]];
    _seg.frame = CGRectMake(20, 10, self.view.frame.size.width  - 40 , 40);

    _seg.tintColor= [UIColor colorWithRed:28 / 255.f green:132 / 255.f blue:100 / 255.f alpha:1.f];
    
    /** 默认选中的item*/
    [self.background addSubview:_seg];
    _seg.selectedSegmentIndex = 0;

    [_seg addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self createtableView];

    [self handle];
    [self hand];

}


- (void)hand{
    
    self.arrSeg = [NSMutableArray array];
    self.arrDanmusssss = [NSMutableArray array];
    
    NSMutableDictionary *dic = @{@"App-Id" : @"10101027",
                                @"Device-Id" : @"616b51f3e3729568db23640554991556",
                                @"Device-V" : @"aVBob25lIE9TXzkuMi4xXzY0MCoxMTM2XzEwMDAwMTAwMF9pUGhvbmUgNVM="}.mutableCopy;
    
    [MHNetWorkTask getWithURL:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&offset=0&size=20&v=2&videoId=%ld",self.ida] withParameter:nil withHttpHeader:dic withResponseType:ResponseTypeJSON withSuccess:^(id result) {
        
        NSArray *arrcomments = [result objectForKey:@"comments"];
        
        for (NSDictionary *diccomments in arrcomments) {
  
            ModelTrailer *model = [[ModelTrailer alloc]init];
            
            model.content = [diccomments objectForKey:@"content"];
            model.userName = [diccomments objectForKey:@"userName"];
            model.userHeadImg = [diccomments objectForKey:@"userHeadImg"];
            model.duration = [[diccomments objectForKey:@"duration"]doubleValue];
            
            NSString *text = [diccomments objectForKey:@"content"];
            NSString *imagea = [diccomments objectForKey:@"userHeadImg"];
            NSDictionary *dica = [NSDictionary dictionaryWithObjects:@[imagea, text] forKeys:@[@"avatar", @"content"]];
            [self.arrDanmusssss addObject:dica];
            
            
            [self.arrSeg addObject:model];
        }
        
        [self.tableView reloadData];
    } withFail:^(NSError *error) {

    }];
  
}


- (void)handle{

    self.array = [NSMutableArray array];
    
    ModelTrailer *model =[[ModelTrailer alloc]init];
    model.regdate = [self.arr valueForKey:@"regdate"];
    
    model.descrip = self.desp;
    [self.array addObject:model];
}



/**界面切换*/
- (void)segmentAction:(UISegmentedControl *)seg{
    
    switch (seg.selectedSegmentIndex) {
        case 0:
           
            [self.tableView reloadData];
            
            break;
            
        case 1:

            [self.tableView reloadData];
            
            break;
        default:
            break;
    }

}


- (void)createtableView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 280 - 40)];
    [self.visualView addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MusicPlayerTableViewCell class] forCellReuseIdentifier:@"pool"];

    [self.tableView registerClass:[MusicSegTableViewCell class] forCellReuseIdentifier:@"poo1"];
    
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;

}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.seg.selectedSegmentIndex == 1) {
        
        return self.arrSeg.count;
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"pool1";
    
    MusicSegTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
        if (self.seg.selectedSegmentIndex == 1) {
            if(cell == nil){
                
                cell = [[MusicSegTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }

            ModelTrailer *model2 = self.arrSeg[indexPath.row];
            
            [cell passSeg:model2];
            cell.backgroundColor = [UIColor blackColor];

            return cell;

        }else {
    
            MusicPlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
        
            ModelTrailer *model = self.array[indexPath.row];
            cell.backgroundColor = [UIColor blackColor];
            [cell passModel:model];
        
            return cell;
        }
}


#pragma mark -  播放页面添加轻拍手势
- (void)addGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllSubViews)];
    
    [self.view addGestureRecognizer:tap];
}

//隐藏bottomView
-(void)dismissAllSubViews {
    
    if (self.isTap == NO) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bottomView.alpha = 0;
            
        }];
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.bottomView.alpha = 0.5;
            
        }];
    }
    self.isTap = !self.isTap;
}

#pragma mark - 观察者 观察播放完毕 观察屏幕旋转
- (void)addNotificationCenters {
    //  注册观察者用来观察，是否播放完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//    
//    //  注册观察者来观察屏幕的旋转
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark 播放结束后的代理回调
- (void)moviePlayDidEnd:(NSNotification *)notify {
    
    [_playerButton setImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
    [_player pause];
    _isPlay = 1;

}
//
//#pragma mark - 横屏 竖屏的时候frame的设置
//- (void)statusBarOrientationChange:(NSNotification *)notification {
//    
//    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
//    
//    if (orientation == UIInterfaceOrientationLandscapeRight) {
//        
//        NSLog(@"向右横屏");
//        [self setPlayerLayerFrame];
//    }
//    if (orientation == UIInterfaceOrientationLandscapeLeft) {
//        
//        NSLog(@"向左横屏");
//        [self setPlayerLayerFrame];
//        
//    }
//    if (orientation == UIInterfaceOrientationPortrait) {
//        
//        NSLog(@"竖屏");
//        [self setVerticalFrame];
//    }
//}
//
////  横屏的时候frame
//- (void)setPlayerLayerFrame {
//    
//    self.playerLayer.frame = CGRectMake(5, 5, [UIScreen mainScreen].bounds.size.width - 10, self.playerView.frame.size.height-5);
//}
//
////  竖屏的时候frame
//- (void)setVerticalFrame {
//    
//    self.playerLayer.frame = CGRectMake(5, 5, [UIScreen mainScreen].bounds.size.width - 10, self.playerView.frame.size.height-5);
//}
//

#pragma mark -  添加进度观察 - addProgressObserver
- (void)addProgressObserver {
    
    __block MusicPlayerViewController *vc = self;
    
    //设置(1,1) 设置每秒执行一次
    
    [vc.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue: dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        
        //总时长 将CMTime类型转成float类型
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        
        //当前时间
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        //剩余时间
        CGFloat rem = duration - current;
        
        NSString *totalT = [NSString stringWithFormat:@"%02d:%02d",(int)rem/60 ,(int)rem%60];
        NSString *currenT = [NSString stringWithFormat:@"%02d:%02d",(int)current/60 ,(int)current%60];
        
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@",currenT,totalT];
        self.timeLabel.text = timeStr;
        
        //保存总时长用于手动快进和快退
        self.totalMovieDuration = duration;
        
        
        //设置进度值 当前时间/总时长
        self.slider.value = current/duration;
    }];
}





#pragma mark - 创建视频项目对象
- (void)addAVPlayer {
    
    self.playerView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 280-64)];
    
    self.playerView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.playerView];

    //创建视频项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.url]];
    
    //创建视频播放器对象
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    //创建承载播放器的AVPlayerLayer对象
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    self.playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width , self.playerView.frame.size.height);
    
    //视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    //将播放器添加到playerView的layer层上
    [self.playerView.layer insertSublayer:self.playerLayer atIndex:0];

    // 创建一个 view 放进度条
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 176, self.view.frame.size.width, 40)];
    [self.playerView addSubview:self.bottomView];

   
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(50, 10, self.view.frame.size.width-150, 20)];
    
    [self.bottomView addSubview:self.slider];

    [self.slider setThumbImage:[UIImage imageNamed:@"slider@2x"] forState:UIControlStateNormal];

    self.slider.minimumTrackTintColor = [UIColor whiteColor];
    self.slider.maximumTrackTintColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.3];
    [self.slider addTarget:self action:@selector(ProgressSlider:) forControlEvents:UIControlEventTouchUpInside];
    
    self.playerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playerButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
    self.playerButton.frame = CGRectMake(10, 10, 20, 20);
    [self.bottomView addSubview:self.playerButton];
    [self.playerButton addTarget:self action:@selector(playerButton:) forControlEvents:UIControlEventTouchUpInside];

    self.timeLabel = [[UILabel alloc]init];
    self.timeLabel.frame = CGRectMake(self.bottomView.frame.size.width- 90, 15, 70, 10);
    self.timeLabel.textColor = [UIColor grayColor];
    self.timeLabel.font = [UIFont systemFontOfSize:10];
    [self.bottomView addSubview:self.timeLabel];
    self.timeLabel.text = @"00:00/00:00";
    
    
    
    UIButton *buttonBig =[UIButton buttonWithType:UIButtonTypeCustom];
    buttonBig.frame = CGRectMake(self.bottomView.frame.size.width- 25, 10, 20, 20);
    
    [buttonBig setImage:[UIImage imageNamed:@"xuanzhuan"] forState:UIControlStateNormal];
    
    [self.bottomView addSubview:buttonBig];

    
    [buttonBig addTarget:self action:@selector(xuanzhuan) forControlEvents:UIControlEventTouchUpInside];
}



- (void)xuanzhuan{
    [_playerButton setImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
    [_player pause];
    _isPlay = 1;

    landscape *play = [[landscape alloc]init];
    
    
    play.UrlString = self.url;
    play.receiveModel = _model;
    
    play.arrDanmu = self.arrDanmusssss;
//
    [self showDetailViewController:play sender:nil];

//    [self setPlayerLayerFrame];

}
- (void)ProgressSlider:(UISlider *)sender {
    
    UISlider *slider = sender;
    
    //获取当前时间
    double currentTime = self.totalMovieDuration * slider.value;
    CMTime dragedCMTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
}

- (void)playerButton:(UIButton *)button {

    if (!_isPlay) {
        [_playerButton setImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
        [_player pause];
        _isPlay = 1;
        
    }else{
        [_playerButton setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        [_player play];
        _isPlay = 0;
//        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(refondContr:) userInfo:nil repeats:NO];
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.seg.selectedSegmentIndex == 1) {
        
        return [MusicSegTableViewCell heightForCell:self.arrSeg[indexPath.row]];
        
    }else{
    
        return [MusicPlayerTableViewCell heightForCell:self.array[indexPath.row]];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
